//
//  DounbleBindViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/21.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxRelay

struct UserViewModel {
    //用户名
    let username = BehaviorRelay<String>(value:"guest")
     
    //用户信息
    lazy var userinfo = {
        return self.username.asObservable()
            .map{ $0 == "hangge" ? "您是管理员" : "您是普通访客" }
            .share(replay: 1)
    }()
}

class DounbleBindViewController: UIViewController {

    private let disposeBag = DisposeBag()
    
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var label: UILabel!
    
    var userVM = UserViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "25.双向绑定：<->"
        view.backgroundColor = .white
        
//        test()
        test2()
    }
    
    // 简单的双向绑定
    func test() {
        //将用户名与textField做双向绑定
        userVM.username.asObservable().bind(to: textField.rx.text).disposed(by: disposeBag)
        textField.rx.text.orEmpty.bind(to: userVM.username).disposed(by: disposeBag)
         
        //将用户信息绑定到label上
        userVM.userinfo.bind(to: label.rx.text).disposed(by: disposeBag)
    }
    
    // 使用自定义操作符
    func test2() {
        //将用户名与textField做双向绑定
        _ =  self.textField.rx.textInput <->  self.userVM.username

        //将用户信息绑定到label上
        userVM.userinfo.bind(to: label.rx.text).disposed(by: disposeBag)
    }
}
